<template>
  <div class="address-container">
    <!-- 顶部导航栏 -->
    <div class="nav-header">
      <div class="back-icon" @click="router.back()">←</div>
      <h2>地址管理</h2>
      <div class="add-icon" @click="showAddDialog = true">+</div>
    </div>

    <!-- 地址列表 -->
    <div class="address-list" v-if="addresses.length > 0">
      <div v-for="address in addresses" :key="address.id" class="address-item" @click="selectAddress(address)">
        <div class="address-info">
          <div class="user-info">
            <span class="username">{{ address.username }}</span>
            <span class="phone">{{ address.phone }}</span>
          </div>
          <div class="address-text">{{ address.address }}</div>
          <div class="address-time">{{ address.time }}</div>
        </div>
        <div class="address-actions">
          <button class="edit-btn" @click.stop="editAddress(address)">编辑</button>
          <button class="delete-btn" @click.stop="deleteAddress(address.id)">删除</button>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <p>暂无地址信息</p>
    </div>

    <!-- 新增/编辑地址弹窗 -->
    <div class="dialog" v-if="showAddDialog || showEditDialog">
      <div class="dialog-content">
        <h3>{{ isEditing ? '编辑地址' : '新增地址' }}</h3>
        <form @submit.prevent="handleSubmit" class="address-form">
          <div class="form-group">
            <input
              type="text"
              v-model="formData.username"
              placeholder="收货人姓名"
              required
            />
          </div>
          <div class="form-group">
            <input
              type="tel"
              v-model="formData.phone"
              placeholder="手机号码"
              required
              pattern="[0-9]{11}"
            />
          </div>
          <div class="form-group">
            <textarea
              v-model="formData.address"
              placeholder="详细地址"
              required
            ></textarea>
          </div>
          <div class="form-group">
            <input
              type="text"
              v-model="formData.time"
              placeholder="送达时间"
              required
            />
          </div>
          <div class="dialog-buttons">
            <button type="button" @click="closeDialog">取消</button>
            <button type="submit">确定</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()
const addresses = ref([])
const showAddDialog = ref(false)
const showEditDialog = ref(false)
const isEditing = ref(false)
const currentEditId = ref(null)

// 选择地址
const selectAddress = (address) => {
  // 如果是从结算页面跳转来的，选择地址后返回结算页面
  if (route.query.from === 'settlement') {
    router.push({
      path: '/shopping/settlement',
      query: { addressId: address.id }
    })
  }
}

const formData = ref({
  username: '',
  phone: '',
  address: '',
  time: ''
})

// 获取地址列表
const fetchAddresses = async () => {
  try {
    const response = await fetch('http://localhost:3005/address/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    const data = await response.json()
    if (data.success === '成功') {
      addresses.value = data.result
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
  }
}

// 新增地址
const addAddress = async () => {
  try {
    const response = await fetch('http://localhost:3005/address/insert', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(formData.value)
    })
    const data = await response.json()
    if (data.success === '成功') {
      await fetchAddresses()
      closeDialog()
    }
  } catch (error) {
    console.error('新增地址失败:', error)
  }
}

// 编辑地址
const editAddress = (address) => {
  console.log('开始编辑地址:', address)
  currentEditId.value = address.id
  formData.value = { ...address }
  isEditing.value = true
  showEditDialog.value = true
  console.log('设置编辑状态完成，当前表单数据:', formData.value)
}

// 更新地址
const updateAddress = async () => {
  try {
    // 打印当前要更新的数据
    console.log('正在更新地址，ID:', currentEditId.value)
    console.log('更新的表单数据:', formData.value)

    // 格式化时间为MySQL datetime格式
    const formattedTime = formData.value.time.replace('T', ' ').replace('.000Z', '')

    const updateData = {
      id: currentEditId.value,
      username: formData.value.username,
      phone: formData.value.phone,
      address: formData.value.address,
      time: formattedTime
    }

    console.log('发送到服务器的数据:', updateData)

    const response = await fetch('http://localhost:3005/address/update', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(updateData)
    })

    // 检查响应状态
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const data = await response.json()
    console.log('服务器响应:', data)

    if (data.success === '成功') {
      alert('地址更新成功！')
      await fetchAddresses()
      closeDialog()
    } else {
      throw new Error(data.err || '更新失败')
    }
  } catch (error) {
    console.error('更新地址失败:', error)
    alert('更新失败: ' + error.message)
  }
}

// 删除地址
const deleteAddress = async (id) => {
  if (!confirm('确定要删除这个地址吗？')) return
  
  try {
    const response = await fetch('http://localhost:3005/address/delete', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ id })
    })
    const data = await response.json()
    if (data.success === '成功') {
      await fetchAddresses()
    }
  } catch (error) {
    console.error('删除地址失败:', error)
  }
}

// 处理表单提交
const handleSubmit = async (event) => {
  event.preventDefault()
  console.log('表单提交，当前模式:', isEditing.value ? '编辑' : '新增')
  
  try {
    if (isEditing.value) {
      await updateAddress()
    } else {
      await addAddress()
    }
  } catch (error) {
    console.error('保存地址失败:', error)
    alert('保存失败: ' + error.message)
  }
}

// 关闭弹窗
const closeDialog = () => {
  showAddDialog.value = false
  showEditDialog.value = false
  isEditing.value = false
  currentEditId.value = null
  formData.value = {
    username: '',
    phone: '',
    address: '',
    time: ''
  }
}

onMounted(() => {
  fetchAddresses()
})
</script>

<style scoped>
.address-container {
  width: 100%;
  padding-bottom: 80px;
  margin-top: 30px;
  background-color: #f7f8fa;
  min-height: 100%;
}

.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: linear-gradient(135deg, #42b883 0%, #35495e 100%);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  color: white;
  height: 50px;
}

.back-icon,
.add-icon {
  font-size: 24px;
  cursor: pointer;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.1);
}

.back-icon:hover,
.add-icon:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: scale(1.05);
}

.nav-header h2 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.address-list {
  padding: 60px 0 0;
  width: 400px;
  margin: 0 auto;
}

.address-item {
  background: white;
  border-radius: 0;
  padding: 16px;
  margin-bottom: 10px;
  box-shadow: none;
  transition: all 0.3s ease;
  border-bottom: 1px solid #f0f0f0;
}

.address-item:hover {
  transform: none;
  box-shadow: none;
  background: #fafafa;
}

.address-info {
  margin-bottom: 12px;
}

.user-info {
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.username {
  font-weight: 600;
  font-size: 15px;
  color: #333;
}

.phone {
  color: #666;
  font-size: 13px;
  background: #f5f7fa;
  padding: 2px 8px;
  border-radius: 10px;
}

.address-text {
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 8px;
  color: #444;
}

.address-time {
  color: #999;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.address-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  padding-top: 8px;
  border-top: 1px solid #f5f5f5;
}

.edit-btn,
.delete-btn {
  padding: 6px 16px;
  border-radius: 14px;
  font-size: 13px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.edit-btn {
  background: #42b883;
  color: white;
  border: none;
}

.edit-btn:hover {
  background: #3aa876;
}

.delete-btn {
  background: white;
  color: #ff4d4f;
  border: 1px solid #ff4d4f;
}

.delete-btn:hover {
  background: #fff1f0;
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  color: #999;
}

.empty-state::before {
  content: "📍";
  font-size: 48px;
}

.dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog-content {
  background: white;
  border-radius: 12px;
  padding: 20px;
  width: 92%;
  max-width: 500px;
  animation: slideUp 0.3s ease;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
}

.dialog-content h3 {
  margin: 0 0 20px;
  text-align: center;
  color: #35495e;
  font-size: 18px;
  font-weight: 600;
}

.address-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-group input,
.form-group textarea {
  width: 450px;
  padding: 12px;
  border: 1px solid #eee;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s ease;
  background: #f9f9f9;
  color: #000;
}

.form-group input:focus,
.form-group textarea:focus {
  border-color: #42b883;
  background: white;
  outline: none;
  box-shadow: 0 0 0 2px rgba(66, 184, 131, 0.1);
}

.form-group textarea {
  height: 100px;
  resize: none;
  line-height: 1.5;
}

.dialog-buttons {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-buttons button {
  padding: 10px 24px;
  border-radius: 8px;
  border: none;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.dialog-buttons button[type="button"] {
  background: #f5f5f5;
  color: #666;
}

.dialog-buttons button[type="button"]:hover {
  background: #eee;
}

.dialog-buttons button[type="submit"] {
  background: #42b883;
  color: white;
  box-shadow: 0 2px 6px rgba(66, 184, 131, 0.2);
}

.dialog-buttons button[type="submit"]:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(66, 184, 131, 0.3);
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideUp {
  from { 
    transform: translateY(20px);
    opacity: 0;
  }
  to { 
    transform: translateY(0);
    opacity: 1;
  }
}
</style>